<script lang="tsx" setup>
import { FormSchema } from '@/types/form'
import { TableColumn } from '@/types/table'
import * as CktApi from '@/api/creative/chuangkit'
import CktDesign from '@chuangkit/chuangkit-design'
import { onMounted, onBeforeUnmount } from 'vue'
import { ElButton, ElMessageBox, ElImage, ElTag } from 'element-plus'
import { getOSSURL } from '@/utils/oss'

// 用户id
const userFlag = '001'
const appId = '1cf71fc825044b6ea6858ce9bbd8b663'

/** 表格字段 */
const columns: TableColumn[] = [
  {
    field: 'selection',
    type: 'selection'
  },
  {
    field: 'thumbUrl',
    label: '缩略图',
    formatter: (_: Recordable, __: TableColumn, cellValue: string) => {
      const url = getOSSURL(cellValue)
      return cellValue ? (
        <ElImage
          class="w-20 h-20"
          src={url}
          preview-src-list={[url]}
          fit="cover"
          preview-teleported
        />
      ) : (
        <span>暂无图片</span>
      )
    }
  },
  {
    field: 'designTitle',
    label: '标题'
  },
  {
    field: 'kindName',
    label: '类别',
    formatter: (_: Recordable, __: TableColumn, cellValue: string) => {
      return <ElTag>{cellValue}</ElTag>
    }
  },
  {
    field: 'updateTime',
    label: '最后编辑',
    formatter: (_, __, value) => {
      return new Date(value).toLocaleString()
    }
  },
  {
    field: 'action',
    label: '操作',
    formatter: (row: Recordable, _: TableColumn, __: string) => {
      return (
        <div>
          <ElButton link type="primary" onClick={() => handleRename(row)}>
            重命名
          </ElButton>
          <ElButton link type="primary" onClick={() => handleEdit(row)}>
            编辑
          </ElButton>
          <ElButton link type="primary" onClick={() => handleCopy(row.designId)}>
            生成副本
          </ElButton>
          <ElButton link type="danger" onClick={() => delList(row.designId, false)}>
            删除
          </ElButton>
        </div>
      )
    }
  }
]

/** 列表相关方法 */
const {
  register: tableRegister,
  tableObject,
  tableMethods
} = useTable({
  getListApi: async (option: any) => {
    const { pageSize, pageNo, ...params } = option

    const newParams = Object.entries(params).reduce((prev, [key, value]) => {
      value && (prev[key] = value)
      return prev
    }, {})

    const { list, total } = await CktApi.listUserDesigns({
      userFlag,
      kindId: 0,
      timeOrder: 0,
      terminal: 0,
      pageNo,
      pageSize,
      designName: ''
    })

    return {
      list,
      total
    }
  },
  delListApi: async (option) => {
    console.log('delete', option)
    await CktApi.deleteDesign({
      userFlag,
      designIds: option,
      terminal: 0
    })
    // 等待半秒再刷新
    await new Promise((resolve) => setTimeout(resolve, 500))
    return {}
  }
})
const { getList, setSearchParams, delList, setProps } = tableMethods

/** 初始化时加载列表 */
const init = async () => {
  getList()
}
init()

/** 搜索栏 */
const searchFields: FormSchema[] = [
  {
    field: 'name',
    label: '标题',
    component: 'Input',
    colProps: { span: 5 }
  }
]

// 编辑器对象
let designEditor: any = null
let multipleSelection = ref<{ design_id: string }[]>([{ design_id: '1' }])

// 是否加载
onMounted(() => {
  // ;(window as any)['chuangkitComplete'] = () => {
  //   loadList()
  // }
})

onBeforeUnmount(() => {
  designEditor && designEditor.close()
})

const sleep = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms))

// 生成副本
const handleCopy = async (designId: string) => {
  setProps({ loading: true })
  await CktApi.copyDesign({
    userFlag,
    designId: designId,
    terminal: 0
  })
  await sleep(500)
  await getList()
  setProps({ loading: false })
}

// 用户重命名
const handleRename = async (row) => {
  const { value } = await ElMessageBox.prompt('重命名', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    inputPattern: /^.+$/,
    inputErrorMessage: '名称有误'
  })

  setProps({ loading: true })
  await CktApi.updateTitle({
    userFlag,
    designId: row.designId,
    title: value,
    terminal: 0
  })
  await sleep(1000)
  await getList()
  setProps({ loading: false })
}

// 用户点击编辑
const handleEdit = async (row: any) => {
  // 付费调起模板编辑器
  const payConfig = { charge_type: 2 }
  // 调用接口获取packageId
  const packageId = await CktApi.requestPackageId()

  // 如果能获取到付费id，则更改
  if (packageId) {
    payConfig.charge_type = 1
    payConfig['package_id'] = packageId
  }
  // 需要签名
  const needSign = {
    app_id: appId,
    // 用户id
    user_flag: userFlag,
    expire_time: Date.now() + 2 * 60 * 1000,
    device_type: 1,
    template_id: row.templateIds[0],
    setting_code: 'RBGJ',
    ...payConfig,
    charging_template_limit: 2,
    coop_font_limit: 2,
    coop_material_limit: 2
  }
  console.log(row)
  // 获取sign接口
  const sign = await CktApi.getTemplateEditorSign(needSign)
  designEditor = new CktDesign({
    ...needSign,
    sign,
    show_name: '1',
    show_watermark: '1'
  })
  designEditor.open()
  // 设置文件名称，在pro-posters-editor中接收
  ;(window as any).$emit('setSourceName', { fileName: row.designTitle })
}

// 创建空白页
const handleCreateBlankDesign = async () => {
  const needSign = {
    appId,
    userFlag,
    expire_time: Date.now() + 1000 * 1000,
    device_type: 1,
    kind_id: 447,
    charge_type: 2,
    // package_id: ""

    charging_template_limit: 2,
    coop_font_limit: 2,
    coop_material_limit: 2
  }
  // 获取sign
  const sign = await CktApi.getTemplateEditorSign(needSign)
  console.log(sign)
  const design = new CktDesign({
    ...needSign,
    sign,
    show_name: '1'
  })
  design.open()
  console.log(design)
}
</script>

<template>
  <!-- 搜索工作栏 -->
  <ContentWrap>
    <Search :schema="searchFields" @search="setSearchParams">
      <template #actionMore>
        <el-button type="primary" @click="openForm('create')" v-hasPermi="['train:course:create']">
          <Icon icon="ep:plus" class="mr-5px" /> 添加
        </el-button>
        <!-- <el-button type="primary" @click="handleCreateBlankDesign"> 创建空白页 </el-button> -->
      </template>
    </Search>
  </ContentWrap>

  <!-- 列表 -->
  <ContentWrap>
    <Table
      @register="tableRegister"
      :columns="columns"
      :data="tableObject.tableList"
      row-key="id"
      :loading="tableObject.loading"
      :pagination="{ total: tableObject.total }"
      v-model:pageSize="tableObject.pageSize"
      v-model:currentPage="tableObject.currentPage"
    />
  </ContentWrap>
</template>
